<template>
  <div class="app-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span class="title">三修基金项目管理</span>
          <div class="right">
            <el-button type="primary" @click="handleAdd">新增项目</el-button>
          </div>
        </div>
      </template>

      <!-- 搜索区域 -->
      <el-form :model="queryParams" ref="queryForm" :inline="true" class="search-form">
        <el-form-item label="项目名称" prop="projectName">
          <el-input
            v-model="queryParams.projectName"
            placeholder="请输入项目名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="项目类型" prop="projectType">
          <el-select v-model="queryParams.projectType" placeholder="请选择项目类型" clearable style="width: 200px">
            <el-option
              v-for="item in projectTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="项目时间" prop="dateRange">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            @change="handleDateRangeChange"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 数据表格 -->
      <el-table
        v-loading="loading"
        :data="projectList"
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" type="index" width="80" align="center" />
        <el-table-column prop="projectName" label="项目名称" min-width="150" show-overflow-tooltip />
        <el-table-column prop="projectType" label="项目类型" width="120">
          <template #default="{ row }">
            {{ getProjectTypeName(row.projectType) }}
          </template>
        </el-table-column>
        <el-table-column prop="targetFund" label="目标金额" width="120">
          <template #default="{ row }">
            ¥ {{ row.targetFund }}
          </template>
        </el-table-column>
        <el-table-column prop="raisedFund" label="已筹金额" width="120">
          <template #default="{ row }">
            ¥ {{ row.raisedFund }}
          </template>
        </el-table-column>
        <el-table-column label="筹款进度" width="180">
          <template #default="{ row }">
            <el-progress 
              :percentage="calculateProgress(row.raisedFund, row.targetFund)" 
              :format="format => `${format}%`"
            />
          </template>
        </el-table-column>
        <el-table-column prop="startDate" label="开始日期" width="120" />
        <el-table-column prop="endDate" label="结束日期" width="120" />
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
            <el-button type="primary" link @click="handleDetail(row)">详情</el-button>
            <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />

      <!-- 添加/编辑对话框 -->
      <el-dialog
        :title="dialogTitle"
        v-model="dialogVisible"
        width="650px"
        append-to-body
        destroy-on-close
      >
        <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="100px"
          class="project-form"
        >
          <el-form-item label="项目名称" prop="projectName">
            <el-input v-model="form.projectName" placeholder="请输入项目名称" />
          </el-form-item>
          <el-form-item label="项目类型" prop="projectType">
            <el-select v-model="form.projectType" placeholder="请选择项目类型" style="width: 100%">
              <el-option
                v-for="item in projectTypeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="项目简介" prop="projectIntro">
            <el-input
              v-model="form.projectIntro"
              type="textarea"
              :rows="3"
              placeholder="请输入项目简介"
            />
          </el-form-item>
          <el-form-item label="项目进度" prop="progressArray">
            <div class="progress-input-container">
              <div v-for="(item, index) in progressItems" :key="index" class="progress-item">
                <el-date-picker
                  v-model="progressItems[index].date"
                  type="date"
                  placeholder="选择日期"
                  value-format="YYYY-MM-DD"
                  class="progress-date"
                />
                <el-input 
                  v-model="progressItems[index].content" 
                  placeholder="请输入进度内容" 
                  class="progress-input"
                />
                <el-button type="danger" icon="Delete" circle @click="removeProgressItem(index)" />
              </div>
              <div class="progress-add">
                <el-button type="primary" @click="addProgressItem">添加进度</el-button>
                <el-button type="info" @click="addExampleProgressData">使用示例数据</el-button>
              </div>
            </div>
          </el-form-item>
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="已筹金额" prop="raisedFund">
                <el-input-number
                  v-model="form.raisedFund"
                  :precision="2"
                  :step="100"
                  :min="0"
                  style="width: 100%"
                  placeholder="请输入已筹金额"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="目标金额" prop="targetFund">
                <el-input-number
                  v-model="form.targetFund"
                  :precision="2"
                  :step="100"
                  :min="0"
                  style="width: 100%"
                  placeholder="请输入目标金额"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="开始日期" prop="startDate">
                <el-date-picker
                  v-model="form.startDate"
                  type="date"
                  placeholder="请选择开始日期"
                  style="width: 100%"
                  value-format="YYYY-MM-DD"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="结束日期" prop="endDate">
                <el-date-picker
                  v-model="form.endDate"
                  type="date"
                  placeholder="请选择结束日期"
                  style="width: 100%"
                  value-format="YYYY-MM-DD"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitForm">确认</el-button>
          </div>
        </template>
      </el-dialog>

      <!-- 详情对话框 -->
      <el-dialog
        title="项目详情"
        v-model="detailDialogVisible"
        width="600px"
        append-to-body
        destroy-on-close
      >
        <div v-if="detailForm" class="project-detail">
          <el-descriptions :column="1" border>
            <el-descriptions-item label="项目名称">{{ detailForm.projectName }}</el-descriptions-item>
            <el-descriptions-item label="项目类型">{{ getProjectTypeName(detailForm.projectType) }}</el-descriptions-item>
            <el-descriptions-item label="项目简介">{{ detailForm.projectIntro }}</el-descriptions-item>
            <el-descriptions-item label="项目进度">
              <div v-if="detailForm.progressArray">
                <el-timeline>
                  <el-timeline-item
                    v-for="(progress, index) in parseProgressArray(detailForm.progressArray)"
                    :key="index"
                    :timestamp="progress.date"
                  >
                    {{ progress.content }}
                  </el-timeline-item>
                </el-timeline>
              </div>
              <span v-else>暂无进度记录</span>
            </el-descriptions-item>
            <el-descriptions-item label="筹款情况">
              <div class="fund-progress">
                <div class="fund-info">
                  <span>已筹：¥ {{ detailForm.raisedFund }}</span>
                  <span>目标：¥ {{ detailForm.targetFund }}</span>
                </div>
                <el-progress 
                  :percentage="calculateProgress(detailForm.raisedFund, detailForm.targetFund)" 
                  :format="format => `${format}%`"
                />
              </div>
            </el-descriptions-item>
            <el-descriptions-item label="项目时间">
              {{ detailForm.startDate }} 至 {{ detailForm.endDate }}
            </el-descriptions-item>
            <el-descriptions-item label="创建时间">{{ formatDate(detailForm.createTime) }}</el-descriptions-item>
          </el-descriptions>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import FundProjectAPI from '@/api/genealogy/fund-project.api'
import Pagination from '@/components/Pagination'
import { parseTime } from '@/utils'

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  projectName: '',
  projectType: undefined,
  beginTime: undefined,
  endTime: undefined
})

// 表单参数
const form = reactive({
  id: undefined,
  projectName: '',
  projectType: undefined,
  projectIntro: '',
  progressArray: '',
  raisedFund: 0,
  targetFund: 0,
  startDate: '',
  endDate: '',
  createTime: undefined
})

// 表单校验规则
const rules = {
  projectName: [{ required: true, message: '请输入项目名称', trigger: 'blur' }],
  projectType: [{ required: true, message: '请选择项目类型', trigger: 'change' }],
  projectIntro: [{ required: true, message: '请输入项目简介', trigger: 'blur' }],
  targetFund: [{ required: true, message: '请输入目标金额', trigger: 'blur' }],
  startDate: [{ required: true, message: '请选择开始日期', trigger: 'change' }],
  endDate: [{ required: true, message: '请选择结束日期', trigger: 'change' }]
}

// 项目类型选项
const projectTypeOptions = ref([
  { value: '修祠', label: '修祠' },
  { value: '修谱', label: '修谱' },
  { value: '修墓', label: '修墓' },
  { value: '其他', label: '其他' }
])

// 页面数据
const loading = ref(false)
const projectList = ref([])
const total = ref(0)
const dateRange = ref([])
const selectedRows = ref([])
const dialogVisible = ref(false)
const dialogTitle = ref('')
const detailDialogVisible = ref(false)
const detailForm = ref(null)
const formRef = ref(null)
const queryForm = ref(null)
const progressItems = ref([]) // 项目进度项数组，每项包含日期和内容

// 获取列表数据
const getList = async () => {
  loading.value = true
  try {
    const res = await FundProjectAPI.getPage(queryParams)
    projectList.value = res.list || []
    total.value = res.total || 0
  } catch (error) {
    console.error('获取三修基金项目列表失败', error)
    ElMessage.error('获取三修基金项目列表失败')
  } finally {
    loading.value = false
  }
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return ''
  return parseTime(date, '{y}-{m}-{d}')
}

// 计算筹款进度百分比
const calculateProgress = (raised, target) => {
  if (!target || target === 0) return 0
  const progress = (raised / target) * 100
  return Math.min(progress, 100).toFixed(2)
}

// 获取项目类型名称
const getProjectTypeName = (type) => {
  const option = projectTypeOptions.value.find(item => item.value === type)
  return option ? option.label : '未知类型'
}

// 处理日期范围变化
const handleDateRangeChange = (val) => {
  if (val) {
    queryParams.beginTime = val[0]
    queryParams.endTime = val[1]
  } else {
    queryParams.beginTime = undefined
    queryParams.endTime = undefined
  }
}

// 查询操作
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

// 重置查询
const resetQuery = () => {
  if (queryForm.value) {
    queryForm.value.resetFields()
  }
  dateRange.value = []
  queryParams.beginTime = undefined
  queryParams.endTime = undefined
  handleQuery()
}

// 多选框选中数据
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 新增操作
const handleAdd = () => {
  resetForm()
  // 初始化一个空的进度项
  progressItems.value = [{
    date: '',
    content: ''
  }]
  dialogTitle.value = '新增三修基金项目'
  dialogVisible.value = true
}

// 添加示例进度数据（用于测试）
const addExampleProgressData = () => {
  progressItems.value = [
    {
      date: '2024-03-20',
      content: '项目正式启动，开始收集家族历史资料'
    },
    {
      date: '2024-03-15',
      content: '完成项目前期调研和方案设计'
    },
    {
      date: '2024-03-10',
      content: '获得家族理事会批准'
    }
  ]
}

// 编辑操作
const handleEdit = async (row) => {
  resetForm()
  dialogTitle.value = '编辑三修基金项目'
  
  try {
    const res = await FundProjectAPI.getFormData(row.id)
    Object.assign(form, res)
    progressItems.value = progressStringToItems(form.progressArray)
    dialogVisible.value = true
  } catch (error) {
    console.error('获取三修基金项目表单数据失败', error)
    ElMessage.error('获取三修基金项目表单数据失败')
  }
}

// 详情操作
const handleDetail = async (row) => {
  try {
    const res = await FundProjectAPI.getFormData(row.id)
    detailForm.value = res
    detailDialogVisible.value = true
  } catch (error) {
    console.error('获取三修基金项目详情失败', error)
    ElMessage.error('获取三修基金项目详情失败')
  }
}

// 删除操作
const handleDelete = (row) => {
  const ids = row.id || selectedRows.value.map(item => item.id).join(',')
  if (!ids) {
    ElMessage.warning('请选择至少一条记录')
    return
  }
  
  ElMessageBox.confirm('确认删除所选三修基金项目吗？', '警告', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    FundProjectAPI.deleteByIds(ids).then(() => {
      ElMessage.success('删除成功')
      getList()
    }).catch(error => {
      console.error('删除三修基金项目失败', error)
      ElMessage.error('删除三修基金项目失败')
    })
  })
}

// 重置表单
const resetForm = () => {
  form.id = undefined
  form.projectName = ''
  form.projectType = undefined
  form.projectIntro = ''
  form.progressArray = ''
  form.raisedFund = 0
  form.targetFund = 0
  form.startDate = ''
  form.endDate = ''
  form.createTime = undefined
  progressItems.value = []
  
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

// 提交表单
const submitForm = () => {
  if (!formRef.value) return
  
  formRef.value.validate(async (valid) => {
    if (!valid) return
    
    try {
      loading.value = true
      
      // 处理项目进度
      form.progressArray = progressItemsToString()
      
      if (form.id) {
        // 更新
        await FundProjectAPI.update(form.id, form)
        ElMessage.success('修改成功')
      } else {
        // 新增
        await FundProjectAPI.create(form)
        ElMessage.success('新增成功')
      }
      
      dialogVisible.value = false
      getList()
    } catch (error) {
      console.error('保存三修基金项目失败', error)
      ElMessage.error('保存三修基金项目失败')
    } finally {
      loading.value = false
    }
  })
}

// 添加进度项
const addProgressItem = () => {
  progressItems.value.push({
    date: '',
    content: ''
  })
}

// 删除进度项
const removeProgressItem = (index) => {
  progressItems.value.splice(index, 1)
}

// 将进度项数组转换为字符串
const progressItemsToString = () => {
  return JSON.stringify(progressItems.value.filter(item => item.date && item.content.trim() !== ''))
}

// 将进度字符串转换为数组
const progressStringToItems = (progressStr) => {
  if (!progressStr) return []
  try {
    return JSON.parse(progressStr)
  } catch (error) {
    console.error('解析进度数据失败', error)
    return []
  }
}

// 解析进度数组用于详情显示
const parseProgressArray = (progressArray) => {
  if (!progressArray) return []
  try {
    const progressItems = JSON.parse(progressArray)
    // 按日期降序排列，最新的在前面
    return progressItems.sort((a, b) => new Date(b.date) - new Date(a.date))
  } catch (error) {
    console.error('解析进度数据失败', error)
    return []
  }
}

// 页面加载时获取数据
onMounted(() => {
  getList()
})
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title {
  font-size: 18px;
  font-weight: bold;
}

.search-form {
  margin-bottom: 20px;
}

.project-form {
  max-height: 500px;
  overflow-y: auto;
}

.progress-input-container {
  display: flex;
  flex-direction: column;
  width: 100%;
}

.progress-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  width: 100%;
}

.progress-date {
  width: 150px;
  margin-right: 10px;
}

.progress-input {
  flex: 1;
  margin-right: 10px;
}

.progress-add {
  margin-top: 10px;
}

.fund-progress {
  width: 100%;
}

.fund-info {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
}

.project-detail {
  max-height: 600px;
  overflow-y: auto;
}
</style>
